<?php
class  ApiCenter_ProductApi_Model_Api2_Product  extends  Mage_Api2_Model_Resource {
    const ATTRIBUTE_CODE = 'media_gallery';
    
    const DEFULT_VISIBILITY = "1";
     
    const DEFULT_STAUTS = "2";
     
    const DEFULT_APPROVAL = "0";
    
    const  WEBSITEID = "1";
    
    const CN = "3";
    
    private   $step_main=array(
        "General",
        "Basic Product Information",
        "Prices",
    );
    
    
    private  $step1Map = array(
        "name",
        "common_product_name",
        "description",
        "short_description",
        "common_reasons"
    );
    private  $step2Map = array(
        "common_brand",
        "price",
        "special_price",
        "special_from_date",
        "special_to_date",
        "common_other_platform_link",
        "common_other_platform_price",
        "common_is_charged",
        "common_msds",
        "common_package_length",
        "common_package_width",
        "common_package_height",
        "common_shipping_type",
        "common_warehouse_code",
    );
    
    private  $imageMap = array(
        "image"=>"is_main",
        "small_image"=>"is_smallimage",
        "thumbnail"=>"is_thumbnail",
    );
    private   $step_3 =array(
        "Additional Product Information",
    );
    private $filterArr = array(
       "pulscen",
       "giftcard_amounts",
       "allow_open_amount",
       "common_weight",
       "open_amount_min",
       "open_amount_max",
       "group_price",
       "tier_price",
       "common_supply_price",
       "msrp_enabled",
       "msrp_display_actual_price_type",
       "common_supplier_special_price",
        "attr_giftcard_amounts",
        "fb_product",
       "news_from_date",
       "news_to_date",
       "url_key",
       "country_of_manufacture",
       "is_returnable",
       "em_featured",
       "em_deal",
       "em_hot",
       "yml",
        "sku",
       "vendor_id",
        "visibility",
       "status",
        "approval",
       "yandex_market_product_category",
       "tax_class_id",
       "tiers_table",
       "msrp",
        "cost",
       "common_other_shipping_type",
       "common_publish_platform",
       "common_shipping_method",
       "common_dimensional_weight",
       "inventory_manage_stock",
       "inventory_min_sale_qty",
       "inventory_max_sale_qty",
       "inventory_is_qty_decimal",
       "inventory_notify_stock_qty",
       "inventory_enable_qty_increments",
       "inventory_backorders",
       "simple_product_visibility",
    );
    private $childAttr =array(
        "weight",
        "vendor_sku",
    );
    public  $stock_qty=array(
        "attribute_code" => "qty",
        "frontend_label" => "库存",
        "is_required"  =>"1",
        "frontend_input"=>"text"
    );
    public  $media_gallery = array(
        "attribute_code" => "media_gallery",
        "frontend_label" => "商品图片",
        "is_required"  =>"1",
        "frontend_input"=>"text"
    );
    public $vendor_sku = array(
        "attribute_code" => "vendor_sku",
        "frontend_label" => "商家Sku",
        "is_required"  =>"1",
        "frontend_input"=>"text"
    );
    public $weight = array(
        "attribute_code" => "weight",
        "frontend_label" => "商品重量(kg)",
        "is_required"  =>"1",
        "frontend_input"=>"text"
    );
    private $readonly = array(
        "common_reasons",
         
    );
    private $buildNum = array(
        "price",
        "special_price",
        "weight",
        "common_other_platform_price"
    );
    public $warehouse_code =array(
        "attribute_code" => "common_warehouse_code",
        "frontend_label" => "默认仓库",
        "is_required"  =>"1",
        "frontend_input"=>"select"
    );
    private  $hidden = array(
         
    );
    /**
     * collection 集合
     * 
     * */
    protected function _getCollectionForRetrieveCollection($vendorId){
         
        $collection = Mage::getResourceModel("catalog/product_collection");
        $collection->addAttributeToFilter("vendor_id",$vendorId)
       //->addAttributeToFilter("k.parent_id",array('isnull' => true))
        ->addAttributeToSelect('*');
        $collection->getSelect()
        ->joinLeft(array("k"=>"catalog_product_super_link"), 
                    "k.product_id = e.entity_id",
                    array("parent_id"=>"k.parent_id")
            )
       
        ->where("k.parent_id is NULL");
        
        $collection->joinField('qty',
            'cataloginventory/stock_item',
            'qty',
            'product_id=entity_id',
            '{{table}}.stock_id=1',
            'left');
        $this->_applyCollectionModifiers($collection);

        return $collection;
    }
     
    protected function _getCountForRetrieveCollection($vendorId){
         
        $collection = Mage::getResourceModel("catalog/product_collection");
        $collection->addAttributeToFilter("vendor_id",$vendorId)
        ->addAttributeToSelect('*');
        $collection->getSelect()
        ->joinLeft(array("k"=>"catalog_product_super_link"), 
                    "k.product_id = e.entity_id",
                    array("parent_id"=>"k.parent_id")
            )
        ->where("k.parent_id is NULL");
        $collection->joinField('qty',
            'cataloginventory/stock_item',
            'qty',
            'product_id=entity_id',
            '{{table}}.stock_id=1',
            'left');
        $this->_applyFilter($collection);
        return count($collection);
    }
    
    /**
     * 加载子产品
     * */
    protected function _loadchildproduct($product,$onlySelect = false){
        $products = $product->getTypeInstance(true)
        ->getUsedProducts(null, $product);
        if($onlySelect){
            return $products;
        }
        foreach($products as $_product){
            $data[$_product->getId()] = $this->getConfigurableSettings($_product,$product);
            $this->weight["product_value"] = $this->_getChildWeight($_product->getId());
            $data[$_product->getId()][] =$this->weight;
            $this->vendor_sku["product_value"] = $_product->getVendorSku();
            $data[$_product->getId()][] =$this->vendor_sku;
            $this->stock_qty['product_value'] = (int)$_product->getStockItem()->getQty();
            $data[$_product->getId()][] =$this->stock_qty;
        }
        return $data;
    }
    /**
     * 获取可配置产品的超级属性
     * */
    protected function getConfigurableSettings($product,$main_product) {
        $childOption = Mage::registry("super_option");
        $data = array();
        $attributes = $main_product->getTypeInstance(true)
        ->getUsedProductAttributes($main_product);
        foreach ($attributes as $attribute) {
            $data[] = array(
                'attribute_id' => $attribute->getId(),
                'attribute_code' => $attribute->getAttributeCode(),
                'frontend_label'      => $attribute->getFrontendLabel(),
                'product_value'  => $product->getData($attribute->getAttributeCode()),
                'frontend_input' => $attribute->getFrontendInput(),
                "select_option" =>$childOption[$attribute->getAttributeCode()]
            );
        }
        return $data;
    }
    
    /**
     * 获取子产品的价格
     * $product Mage_Catalog_Model_Product
     **/
    protected  function _getConfigurableAttrPrice($product){
        
        $attributes = $product->getTypeInstance(true)
        ->getConfigurableAttributesAsArray($product);
        	
        if(empty($attributes)){
            return "[]";
        }	
        foreach($attributes as $attribute){
            if(!empty($attribute['values'])){
                foreach($attribute['values'] as $k => $super){
                    $res[$attribute['attribute_id']]['value'][$super['value_index']]['price']=$super['pricing_value']?round($super['pricing_value'],2):0;
                    $res[$attribute['attribute_id']]['value'][$super['value_index']]['id']=$super['value_index'];
                    $res[$attribute['attribute_id']]['value'][$super['value_index']]['name']=$super['store_label'];
                    $res[$attribute['attribute_id']]['attribute_code']=$attribute['attribute_code'];
                    $res[$attribute['attribute_id']]['id']=$attribute['id'];
                }
            }
        } 
    
        return $res;
    }
    
    /**
     * 
     * 加载set_id的属性集 并添加某个属性的值
     * */
    protected function _loadAttrMatchValue($set_id,$product){
        $productInfo=$product->getData();
        $collection = Mage::getResourceModel('catalog/product_attribute_collection')
        ->addStoreLabel(self::CN)
        ->setAttributeSetFilter($set_id)
        ->addVisibleFilter()
        ->load();
        
        $attr = $collection->getData();
        $vendorId  =$this->getRequest()->getParam('vendorid');
        
        
        /* @var $helper ApiCenter_ProductApi_Helper_Data */
        $helper = Mage::helper("productapi");
        /* @var $helper ApiCenter_VendorsApi_Helper_Data */
        $ves_helper = Mage::helper("vendorsapi");
         $product_attr=array(
            "step_1"=>array(
					"name" => "产品描述（步骤一）：",
					"data" => array(),
					),
            "step_2"=>array(
					"name" => "产品信息（步骤二）：",
					"data" => array(),
					),
            "step_3"=>array(
					"name" => "产品规格（步骤三）",
					"data" => array(),
					),
            );
			$other_attr=array(
					"super_attr"=>array(
					),
      
				   "others"=>array(
					
						),
			    
			);
			$main_attr = array(

			);
			$info =array(
			    
			);
        $childOption = array();
        foreach ($attr as $i=>$val){
            $group_name = $helper->getAttributeGroupAction($val['attribute_group_id']);
        
            if($val['frontend_input']== "select"||$val['frontend_input']== "multiselect"){
                $val['select_options']= $helper->getAttributesOption($val['attribute_id']);
            }
            if(in_array($val['attribute_code'], $this->readonly)) $val["read_only"]=1;
            if (in_array($val['attribute_code'], $this->filterArr)) continue;
			
            if(isset($productInfo[$val['attribute_code']])){
                $val["product_value"]=$productInfo[$val['attribute_code']];
                if($val['is_wysiwyg_enabled']=="1"){
                    $val["product_value"] = $helper->restoreMageImage($val["product_value"]);
                }
                if(in_array($val['attribute_code'],$this->buildNum)){
                    $val["product_value"] = round($val["product_value"],2);
                }
                if($val['frontend_input'] == "multiselect"){
                    $val["product_value"] = explode(",",$val["product_value"]);
                }
            }
            
            if(in_array($val['attribute_code'],$this->childAttr)){
                $other_attr["others"][]= $val;
                if($productInfo['type_id']=="configurable"&&$val['attribute_code']!=="weight"){
                    $main_attr[]= $val;
                }
                continue;
            }
            
            if($val['is_global'] == '1' && $val['frontend_input'] == 'select' && $val['is_configurable']){
                array_shift($val['select_options']);
                   if($this->matchImageLabel($val['attribute_id'])){
                       $val['image_label']=1;
                   }
                 $other_attr["super_attr"][]= $val;
                 $childOption[$val['attribute_code']] =$val['select_options'];
                continue;
            }
           
           
            if(in_array($group_name,$this->step_main)){
                $step_main[]=$val;
            }   
            if(in_array($group_name, $this->step_3)){
                $product_attr["step_3"]['data'][]= $val;
            }
        }
        //步骤一
         foreach ($this->step1Map as $attribute){
             foreach ($step_main as $_attribute){
                           if($attribute== $_attribute['attribute_code']){
                                 $product_attr["step_1"]['data'][]=$_attribute;
                           }
                    }
         }
         //步骤二
         foreach ($this->step2Map as $attribute){
             foreach ($step_main as $_attribute){
                 if($attribute== $_attribute['attribute_code']){
                     if($_attribute['attribute_code']=="common_warehouse_code"){
                        $this->warehouse_code['product_value'] =  $_attribute["product_value"];
                        $this->warehouse_code['select_options']=$ves_helper->loadWareHouseOption($vendorId);
                        $_attribute= $this->warehouse_code;
                     }
                     $product_attr["step_2"]['data'][]=$_attribute;
                 }
             }
         }
         
        //临时使用查询出来的超级属性
        Mage::register("super_option", $childOption);
        if($productInfo['type_id']=="configurable"){
            $filter_attr["attr_price"]=$this->_getConfigurableAttrPrice($product);
            $filter_attr["child_product"]=$this->_loadchildproduct($product);
        }else{
            $this->stock_qty["product_value"]=(int)$productInfo['stock_item']->getQty();
        }
        $other_attr["others"][]= $this->stock_qty;
        Mage::unregister("super_option");
        // $main_info 附带商品的其他信息
         $main_info['entity_id'] = $productInfo['entity_id'];
         $main_info['type_id'] = $productInfo['type_id'];
         $main_info['categories'] =$product->getCategoryIds();
         $main_info['set_id'] = $productInfo['attribute_set_id'];
         $main_info['approval'] = $productInfo['approval'];
         $filter_attr["media_gallery"]=$this->_retrunImageInfo($productInfo['media_gallery'],$productInfo['image'],$productInfo['small_image'],$productInfo['thumbnail']);//加载图片属性
         $filter_attr['step']=$product_attr;
         $filter_attr['super']=$other_attr;
         $filter_attr['main'] = $main_attr;
         $filter_attr['main_info'] = $main_info;
        return $filter_attr;
    }
    
    //获取产品重量
    protected function _getChildWeight($id){

        if(!$id){
            return 0;
        }
        $wegiht = Mage::getModel("catalog/product")->load($id)->getWeight();
       return  round($wegiht,2);
    }
    
    protected  function _retrunImageInfo($media_gallery,$image=null,$small_image=null,$thumbnail=null){
        foreach($media_gallery['images'] as $key => $images){
                if($images['file']==$image){
                    $media_gallery['images'][$key][$this->imageMap['image']]=1;
                }
                if($images['file']==$thumbnail){
                    $media_gallery['images'][$key][$this->imageMap['thumbnail']]=1;
                }
                if($images['file']==$small_image){
                    $media_gallery['images'][$key][$this->imageMap['small_image']]=1;
                }
        }
        return $media_gallery['images'];
    }
    protected  function matchImageLabel($superAttrId){
        $str = Mage::getStoreConfig('vendors/catalog/super_attribute_use_configurable_image_label');
   
        $super= explode(",", $str);
        
        if(in_array($superAttrId, $super)){
            return true;
        }
            return false;
    }
}